import React, { useState, useEffect } from 'react';
import { d_sort, for_obj, alert_st, obj_int, is_empty, useHigh, GridTable, useCmd, WaitUmd, MainView, BtTxt, Ret, obj_str, PanelTitle,
    uJob, cline, InfoDlg, Title, loc } from 'sui';
import { useAccess } from 'cache';
import { DlgBuy } from './ctl';
import { show_val } from 'buy/task/cmd';

const Census = ({ data, hreturn, map_custom }) => {
    const [open_info, openInfo] = useState(false);
    const [open_buy, openBuy] = useState(false);
    const [alert, setAlert] = useState();
    const [main, setMain] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd();
    const [no_acc] = useAccess();

    useEffect(() => {
        if (is_empty(data)) {
            setMain(null);
            return;
        }

        const ret = {};

        data.forEach(d => {
            const dnum = obj_int(d, "dnum");
            const sn = obj_str(d, "custom");

            if (ret[sn]) {
                ret[sn] += dnum;
            } else {
                ret[sn] = dnum;
            }
        });

        const set = new Set();

        for_obj(map_custom, (k, d) => {
            const f = ret[k];
            if (!f) {
                return;
            }

            let level = obj_str(d, "level");
            if (!level) {
                return;
            }

            level = obj_int(d, "level");

            if (f <= level) {
                set.add(d.sn);
            }
        });

        const tmp = [];

        for_obj(ret, (k, v) => tmp.push({ custom: k, dnum: v }));

        d_sort(tmp, "custom");

        tmp.forEach((d, i) => d["index"] = i + 1);

        setAlert(set);
        setMain(tmp);
    }, [data, map_custom]);

    const pact = {
        "buy": () => openBuy(true),
    };

    const act = {
        "buy": (v) => {
            umd.startWait();

            uJob(null, "sale/order",
                {
                    line: cline(),
                    v: v,
                },
                r => {
                    umd.endWait();
                    openInfo(true);
                },
                e => umd.setErr());
        }
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: loc("l_131"), key: 'st', width: 70, formatter: (props) => {
            const d = props.row;
            return alert_st(d, alert, "custom");
        }},
        {name: loc("l_109"), key: 'custom', width: 200, formatter: (props) => show_val(props, "custom", map_custom, "name")},
        {name: loc("l_238"), key: 'e_opt', width: 90, formatter: (props) => {
            const d = props.row;
            return (
                <div className="inline-flex">
                    <BtTxt hcmd={() => umd.pact(pact, d, "buy")} disabled={no_acc("uab")}>{loc("l_552")}</BtTxt>
                </div>
            );
        }},
        {name: loc("l_127"), key: 'dnum', width: 70},
        {name: loc("l_122"), key: 'unit', width: 70, formatter: (props) => show_val(props, "custom", map_custom, "unit")},
    ];

    const Left = () => <Title mod={loc("l_113")} sub={loc("l_115")}/>;

    return (
        <MainView>
            <PanelTitle left={<Left/>} right={<Ret hcmd={hreturn}/>} cl="gray"/>
            <GridTable col={col} row={main} high={high}/>
            <DlgBuy open={open_buy} setOpen={openBuy} cur={umd.cur} hcmd={(v) => umd.act(act, v)} map_custom={map_custom}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={loc("l_562")}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {Census};
